package cn.tedu.yushouge.pet.adopt.service.impl;

import cn.tedu.yushouge.commons.ex.ServiceException;
import cn.tedu.yushouge.commons.web.ServiceCode;
import cn.tedu.yushouge.pet.adopt.mapper.PetMapper;
import cn.tedu.yushouge.pet.adopt.mapper.PetPicMapper;
import cn.tedu.yushouge.pet.adopt.pojo.entity.Adopt;
import cn.tedu.yushouge.pet.adopt.pojo.entity.Pet;
import cn.tedu.yushouge.pet.adopt.pojo.entity.PetPic;
import cn.tedu.yushouge.pet.adopt.pojo.param.PetAddNewParam;
import cn.tedu.yushouge.pet.adopt.pojo.param.PetPicAddNewParam;
import cn.tedu.yushouge.pet.adopt.pojo.vo.PetPicListItemVO;
import cn.tedu.yushouge.pet.adopt.pojo.vo.PetPicStandardVO;
import cn.tedu.yushouge.pet.adopt.pojo.vo.PetStandardVO;
import cn.tedu.yushouge.pet.adopt.service.IPetPicService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
@Service
public class PetPicServiceImpl implements IPetPicService {

    @Autowired
    PetPicMapper petPicMapper;

    @Autowired
    PetMapper petMapper;

    @Override
    public void addNew(PetPicAddNewParam petPicAddNewParam,Long petId) {
        log.debug("开始处理【添加宠物图片】的业务，参数：{}", petPicAddNewParam);
        int num = petPicMapper.countPicNum(petId);
        if (num==0){
            String message = "添加宠物图片失败，未查询到该宠物信息！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        if(num>=10){
            String message = "添加宠物图片失败，该宠物图片已达上限10张，如需添加，请删除部分图片！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT,message);
        }
        PetPic petPic = new PetPic();
        petPic.setPetId(petPic.getPetId());
        petPic.setPicUrl(petPicAddNewParam.getPicUrl());
        petPic.setGmtCreate(LocalDateTime.now());
        petPic.setGmtModified(LocalDateTime.now());
        int rows = petPicMapper.insert(petPic);
        if (rows != 1){
            String message = "添加宠物图片失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_INSERT, message);
        }
        log.debug("将新的宠物图片数据写入到数据库，完成！");
    }

    @Override
    public void deleteById(Long id) {
        PetPic petPic = petPicMapper.selectById(id);
        log.debug("开始处理【根据ID删除宠物图片】的业务，参数：{}", id);
        int countById = petPicMapper.countPicNum(id);
        if (countById == 0) {
            String message = "删除宠物图片失败，该宠物图片不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        //检查是否有宠物表关联到了此宠物，如果存在，则抛出异常
        QueryWrapper<Pet> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.eq("id",petPic.getPetId());
        int countByPetId2 = petMapper.selectCount(queryWrapper2);
        log.debug("根据宠物表ID统计匹配的宠物图片数量，结果：{}",countByPetId2);
        if (countByPetId2>0){
            String message = "删除宠物失败，仍然有宠物领养表关联到此宠物";
            log.warn(message);
            throw  new ServiceException(ServiceCode.ERR_CONFLICT,message);
        }

        int rows = petMapper.deleteById(id);
        if (rows != 1){
            String message = "删除宠物图片请求失败，服务器忙，请稍后再试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_DELETE, message);
        }
        log.debug("从宠物图片表删除一条数据，完成！");
    }

    private int updateNotCoverByAlbum(Long petId){
        log.debug("开始处理【根据相册ID将图片设置为\"非封面\"】的数据访问，参数：{}", petId);
        PetPic picture = new PetPic();
        picture.setIsCover(0);
        QueryWrapper<PetPic> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("pet_id",petId);
        int rows = petPicMapper.update(picture,queryWrapper);
        return rows;
    }

    @Override
    public void setCover(Long id) {
        log.debug("开始处理【根据ID将图片设置为封面】的业务，参数：{}", id);

        PetPicStandardVO picture = petPicMapper.getStandardById(id);
        if (picture == null) {
            String message = "设置封面图片失败，尝试访问的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        if (picture.getIsCover() == 1) {
            String message = "设置封面图片失败，此图片已经是所属相册的封面！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_CONFLICT, message);
        }

        Long petId = picture.getPetId();
        PetStandardVO album = petMapper.getStandardById(petId);
        if (album == null) {
            String message = "设置封面图片失败，此图片的相册的数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }

        int row = updateNotCoverByAlbum(petId);
        if (row < 1){
            String message = "设置封面图片失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }


        PetPic newPicture = new PetPic();
        newPicture.setId(id);
        newPicture.setIsCover(1);
        newPicture.setGmtModified(LocalDateTime.now());
        int rows = petPicMapper.updateById(newPicture);
        if (rows != 1) {
            String message = "设置封面图片失败，服务器忙，请稍后再次尝试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_UPDATE, message);
        }
    }

    @Override
    public PetPicStandardVO getStandardById(Long id) {
        log.debug("开始处理【根据ID查询图片详情】的业务，参数：{}", id);
        PetPicStandardVO queryResult = petPicMapper.getStandardById(id);
        if (queryResult == null){
            String message = "查询图片详情失败，图片数据不存在！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND, message);
        }
        return queryResult;
    }

    @Override
    public List<PetPicListItemVO> getPicListByPetId(Long petId) {
        log.debug("开始处理【查询宠物图片】的业务，参数：{}", petId);
        List<PetPicListItemVO> data = petPicMapper.selectPicList(petId);
        if (data==null){
            String message = "未查询到该宠物图片,请稍后重试！";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return data;
    }

    @Override
    public List<PetPicListItemVO> getPicListForIsCover() {
        log.debug("开始处理【查询宠物图片】的业务");
        List<PetPicListItemVO> data = petPicMapper.selectCover();
        if (data==null){
            String message = "没有宠物图片设置为封面";
            log.warn(message);
            throw new ServiceException(ServiceCode.ERR_NOT_FOUND,message);
        }
        return data;
    }
}
